import { callDeepSeek } from './llm/deepseek.js';
import { weatherTool } from './tools/weatherTool.js';

type Tool = typeof weatherTool;

export class AgentRunner {
    private tools: Tool[];

    constructor(tools: Tool[]) {
        this.tools = tools;
    }

    async run(userInput: string): Promise<string> {
        // 你可以把 messages 持久化，用于多轮对话
        const messages = [
            {
                role: 'system' as const,
                content:
                    '你是一名中文助理；当用户询问天气时，请调用工具 getWeather 获取真实天气并用中文自然表达。'
            },
            { role: 'user' as const, content: userInput }
        ];

        const reply = await callDeepSeek({
            messages,
            tools: this.tools.map(t => ({
                name: t.name,
                description: t.description,
                parameters: t.parameters
            }))
        });

        // 如果模型触发了工具调用
        if (reply.tool_calls?.length) {
            const results: string[] = [];
            for (const call of reply.tool_calls) {
                const fnName = call.function.name;
                const args = safeParse(call.function.arguments);
                const tool = this.tools.find(t => t.name === fnName);

                if (!tool) {
                    results.push(`未找到工具：${fnName}`);
                    continue;
                }

                const res = await tool.execute(args);
                results.push(res.content);
            }
            // 这里简单地把工具结果合并返回
            return results.join('\n');
        }

        // 没有调用工具，就把模型的文字回复返回
        return reply.content ?? '（无内容）';
    }
}

function safeParse(json: string): any {
    try {
        return JSON.parse(json || '{}');
    } catch {
        return {};
    }
}
